package com.mjh.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.mjh.bean.User;
import com.mjh.comm.Constant;

/**
 * Servlet Filter implementation class AdminFilter
 */
public class AdminFilter implements Filter {

	private static String[] filterPage;
	
	public static Logger log = Logger.getLogger(AdminFilter.class);
	
    /**
     * Default constructor. 
     */
    public AdminFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		log.info("访问后台：" + req.getRequestURI());
		//for(String page : filterPage){
			//if(req.getRequestURI().matches(page)){
				User user = (User)req.getSession().getAttribute(Constant.LOGIN_KEY);
				if(user == null || user.getStatus() != Constant.USER_NORMAL){
					res.sendRedirect("/admin/login.html");
					return;
				}
			//}
		//}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		String notFilter = fConfig.getInitParameter("filterPage");
		if(notFilter != null){
			filterPage = notFilter.split(";");
		} else {
			filterPage = new String[0];
		}
	}

}
